import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image, 
  ImageBackground,TouchableOpacity,SafeAreaView,
  BackHandler,Dimensions,TextInput,StatusBar
} from 'react-native';
import Toast, {DURATION} from 'react-native-easy-toast'
import BottomView from '../component/BottomView'
import DeviceStorage from '../common/DeviceStorage';
import {BASEURL} from '../api/api'
import {jumpPage} from '../common/common'
import { TipModal } from '../component/Tips';
const dismissKeyboard = require('dismissKeyboard');
const {height, width} = Dimensions.get('window');
export default class Login extends Component{
  static navigationOptions = ({ navigation }) =>{
    return{
      header:null,
    }
  };
  constructor(props){
    super(props);
    this.state = ({
      tel: '',//'18919938190',
      password: '',//'123456',
      edit: this.props.navigation.getParam('edit')
    })
  }
  componentDidMount(){
    
    //BackHandler.addEventListener('hardwareBackPress', ()=>this._handleBackPress);
  }
  componentWillUnmount() {
    //BackHandler.removeEventListener('hardwareBackPress', ()=>this._handleBackPress);
  }
  _handleBackPress(){
    //console.log('login',this.props.navigation)
    //return true;
  }
  _goTo(page,params){
    jumpPage(this.props.navigation,page,params);
    // if(this.props.navigation){
    //   this.props.navigation.push(page);
    // }
  }
  change(val, type){
    if(type == 'tel'){
      this.setState({
        tel: val,
      })
    }
    if(type == 'password'){
      this.setState({
        password: val,
      })
    }
  }
  _login(){
    let edit = this.state.edit;
    dismissKeyboard();
    let {tel, password} = this.state;
    if(!tel){
      this.refs.toast.show("请输入手机号");
      return;
    } else if(tel.length != 11){
      this.refs.toast.show("请输入正确的手机号");
      return;
    } else if(!password){
      this.refs.toast.show("请输入密码");
      return;
    } else {
      this.refs.tipModal._loading();
      fetch(BASEURL+'login?tel='+tel+'&password='+password)
      .then(res => res.json())
      .then(result=>{
        this.refs.tipModal._close();
        //console.log(result);
        if(result.succ == '1'){
          DeviceStorage.save('user',JSON.stringify(result.user));
          this.refs.toast.show("登录成功");
          setTimeout(()=>{
            if(edit == '1'){ //从模板详情页跳过来的
              this.props.navigation.navigate('tempDetail',{
                tempId: this.props.navigation.getParam('tempId'),
                tempTitle: this.props.navigation.getParam('tempTitle'),
                userId: result.user.userId,
                edit:'1'
              });
            } else {
              this._goTo('home');
            }
          },500);
        } else if(result.succ == '2'){
          this.refs.toast.show("用户名或密码错误");
        } else if(result.succ == '0'){
          this.refs.toast.show("登录失败");
        } else{
          this.refs.toast.show("登录失败");
        }
      })
      .catch(err => {
        console.log('err',err);
        this.refs.tipModal._close();
      })
    }
   
  }
  render(){
    return(
      <SafeAreaView style={styles.container}>
        <StatusBar hidden={false} backgroundColor='black' />
        <ImageBackground source={require('../images/login/login_bg.png')} style={{width: width, height: height}}>
          <View style={styles.logView}>
            <Image source={require('../images/login/logo.png')} style={styles.logImg}/>
          </View>
          <View style={styles.inputPView}>
            <Input iconImgStyle={{width:20,height:20}} imgIcon={require('../images/login/icon_tel.png')}  
              onChange={(val) => this.change(val,'tel')} placeholder='手机号' keyboardType='numeric'/>
            <Input iconImgStyle={{width:16,height:22}} imgIcon={require('../images/login/icon_pwd.png')} 
              onChange={(val) => this.change(val,'password')} secureTextEntry={true} placeholder='请填写密码'/>
          </View>
          <View style={styles.loginBtnView}>
            <TouchableOpacity style={styles.loginBtn} onPress={()=>this._login()}>
              <Text style={{color:'white',fontSize:16,fontWeight:'bold'}}>登 录</Text>
            </TouchableOpacity>
            <View style={styles.regView}>
              <SmallBtn text='新用户注册' press={()=>this._goTo('register')}/>
              <View style={{marginRight:30}}></View>
              <SmallBtn text='忘记密码'/>
            </View>
          </View>
          
          <View style={styles.bottomViewStyle}>
            <View>
              <BottomView color='#eee' lineColor='#888' bgColor='transparent' text="第三方登录"/>
            </View>
            
            <View style={styles.bottomView}>
              <Image style={styles.bottomImg} source={require('../images/login/icon_wechat.png')}/>
            </View>
          </View>
        </ImageBackground>
        <Toast ref="toast" position='bottom' positionValue={200} />
        <TipModal ref="tipModal"/>
      </SafeAreaView>
    )
  }
}
class SmallBtn extends Component{
  render(){
    return(
      <TouchableOpacity style={styles.smallBtn} activeOpacity={0.5} onPress={this.props.press} hitSlop={{top: 10, left: 5, bottom: 10, right: 5}}>
        <Text style={{color:'#0066FE',fontSize:14}}>{this.props.text}</Text>
      </TouchableOpacity>
    )
  }
}
class Input extends Component{
  render(){
    return(
      <View style={styles.inputView}>
        <Image style={this.props.iconImgStyle} source={this.props.imgIcon} />
        <TextInput 
          ref={this.props._ref}
          placeholder={this.props.placeholder}
          style={styles.searchInput}
          underlineColorAndroid="transparent"
          onChangeText={this.props.onChange}
          value={this.props.val}
          returnKeyType='search'
          placeholderTextColor='#eee'
          secureTextEntry={this.props.secureTextEntry}
          keyboardType={this.props.keyboardType}
        />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  bottomImg:{
    width:36,
    height:36,
  },
  bottomViewStyle:{
    height:height*0.24,
    // borderColor:'white',
    // borderWidth:StyleSheet.hairlineWidth,
    justifyContent:'center',
    alignItems:'center'
  },
  bottomView:{
    justifyContent: 'center',
    alignItems: 'center',
  },
  regView:{
    height:'5%',
    flexDirection:'row',
    justifyContent:'center',
  },
  loginBtnView:{
    height:height*0.2,
    // borderColor:'white',
    // borderWidth:StyleSheet.hairlineWidth,
    justifyContent: 'center',
  },
  loginBtn:{
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft:40,
    marginRight:40,
    marginBottom:15,
    backgroundColor:'#4D7AEF',
    height:40,
    borderRadius:18,
    
  },
  iconImg:{
    width:20,
    height:20,
  },
  searchInput:{
    marginLeft:15,
    padding:0,
    flex:1,
    height: 46, 
    color: 'white',
  },
  inputView:{
    flexDirection:'row',
    alignItems:'center',
    marginLeft:20,
    marginRight:20,
    borderBottomColor:'#888',
    borderBottomWidth:1,
    //borderWidth:1,
    //borderColor:'white',
  },
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  inputPView:{
    height:height*0.16,
    // borderColor:'white',
    // borderWidth:StyleSheet.hairlineWidth,
  },
  logView:{
    justifyContent: 'center',
    alignItems: 'center',
    height:height*0.4,
    // borderColor:'white',
    // borderWidth:StyleSheet.hairlineWidth,
  },
  logImg:{
    marginTop:width*0.2,
    width:width*0.38,
    height:width*0.38*1.19,
    // borderColor:'white',
    // borderWidth:StyleSheet.hairlineWidth,
  }
})